import Router from 'koa-router'
import axios from 'axios'
import Poi from '../dbs/modules/poi'

let router = new Router({
  prefix: '/search'
})

// 搜索tap接口
router.get('/top', async ctx => {
  // try {
  //   let top = await Poi.find({
  //     name: new RegExp(ctx.query.name),
  //     city: ctx.query.city
  //   })

  //   ctx.body = {
  //     success: true,
  //     top: top.map(item => {
  //       return {
  //         name: item.name,
  //         type: item.type
  //       }
  //     })
  //   }
  // } catch (error) {
  //   ctx.body = {
  //     success: false,
  //     top: [],
  //     msg: error
  //   }
  // }
  let {
    status,
    data: {
      top
    }
  } = await axios.get(`http://cp-tools.cn/search/top`, {
    params: {
      input: ctx.query.input,
      city: ctx.query.city
    }
  })

  if (status === 200) {
    ctx.body = {
      success: true,
      top
    }
  } else {
    ctx.body = {
      success: false,
      top: []
    }
  }
})

router.get('/hotPlace', async ctx => {
  // let city = ctx.store ? ctx.store.geo.position.city : ctx.query.city;
  // try {
  //   let result = await Poi.find({
  //     city,
  //     type: ctx.query.type || '景点'
  //   }).limit(10)

  //   ctx.body = {
  //     success: true,
  //     result: result.map(item => {
  //       return {
  //         name: item.name,
  //         type: item.type
  //       }
  //     })
  //   }
  // } catch (error) {
  //   ctx.body = {
  //     success: false,
  //     top: [],
  //     msg: error
  //   }
  // }
  let city = ctx.store ? ctx.store.geo.position.city : ctx.query.city;
  let {
    status,
    data: {
      result
    }
  } = await axios.get(`http://cp-tools.cn/search/hotPlace`, {
    params: {
      city
    }
  })
  if (status === 200) {
    ctx.body = {
      success: true,
      result
    }
  } else {
    ctx.body = {
      success: false,
      result: []
    }
  }
})

router.get('/resultsByKeywords', async (ctx) => {
  const {
    city,
    keyword
  } = ctx.query;
  // count:一共多少条数据
  // pois：数据
  let {
    status,
    data: {
      count,
      pois
    }
  } = await axios.get(`http://cp-tools.cn/search/resultsByKeywords`, {
    params: {
      city,
      keyword
    }
  })
  ctx.body = {
    count: status === 200 ? count : 0,
    pois: status === 200 ? pois : [],
  }
})
router.get('/products', async (ctx) => {
  let keyword = ctx.query.keyword || '旅游'
  let city = ctx.query.city || '北京'
  let {
    status,
    data: {
      product,
      more
    }
  } = await axios.get('http://cp-tools.cn/search/products', {
    params: {
      keyword,
      city
    }
  })
  if (status === 200) {
    ctx.body = {
      product,
      // 判断是否登录的
      more: ctx.isAuthenticated() ? more : [],
      login: ctx.isAuthenticated()
    }
  } else {
    ctx.body = {
      product: {},
      more: ctx.isAuthenticated() ? more : [],
      login: ctx.isAuthenticated()
    }
  }
})

export default router
